import java.io.*;
import java.lang.reflect.Field;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2022-10-29
 * Time: 20:59
 */

//扫描指定目录,查找所有内容包含指定字符的文件
public class TestDemo3 {
    public static void main(String[] args) throws IOException {
        System.out.println("请输入要查找的文件路径");
        Scanner scanner=new Scanner(System.in);
        String rootDirPath=scanner.next();
        System.out.println("请输入要查找的文件内容");
        String str=scanner.next();
        File dir =new File(rootDirPath);
        if(!dir.isDirectory()) {
            System.out.println("文件路径错误");
            return;
        }
        find(dir,str);
    }


    //开始查找
    public static  void find(File dir,String str) throws IOException {
        //先列出该目录下所有的文件
        File[] files=dir.listFiles();
        //文件夹为空直接返回
        if(files==null){
            return;
        }
        for (File file: files) {
            //如果是文件就判断是否包含指定内容
            if(file.isFile()){
                if(judge(file,str)){
                    System.out.println(file.getCanonicalFile());
                }
            }else{
                //还是文件夹就递归
                find(file,str);
            }
        }
    }

    //判断是否包含指定内容
    public static boolean judge(File file,String str){
        StringBuilder stringBuilder=new StringBuilder();
        try(Reader reader=new FileReader(file)){
            while(true){
                char [] buffer =new char[1024];
                int len=reader.read(buffer,0,buffer.length);
                if(len==-1){
                    break;
                }
                //只用将有用的内容读进去
                stringBuilder.append(buffer,0,len);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return stringBuilder.toString().contains(str);
    }
}
